package com.newsanalysis.controller;

import com.newsanalysis.analysis.NewsAnalysisService;
import com.newsanalysis.crawler.NewsCrawlerManager;
import com.newsanalysis.model.entity.News;
import com.newsanalysis.model.entity.User;
import com.newsanalysis.service.NewsService;
import com.newsanalysis.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {
    
    private final NewsService newsService;
    private final UserService userService;
    private final NewsAnalysisService newsAnalysisService;
    private final NewsCrawlerManager crawlerManager;
    
    // 管理仪表盘
    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // 获取统计信息
        // 1. 新闻总数
        int newsCount = (int) newsService.findAll(null).getTotalElements();
        
        // 2. 用户总数
        List<User> allUsers = userService.findAll();
        int userCount = allUsers.size();
        
        // 3. 热门新闻
        List<News> hotNews = newsService.findTopHotNews(5);
        
        // 4. 新闻类别分布
        Map<String, Long> categoryDistribution = newsAnalysisService.analyzeCategoryDistribution();
        
        // 5. 情感倾向分布
        Map<String, Long> sentimentDistribution = newsAnalysisService.analyzeSentimentDistribution();
        
        // 设置数据到请求
        model.addAttribute("newsCount", newsCount);
        model.addAttribute("userCount", userCount);
        model.addAttribute("hotNews", hotNews);
        model.addAttribute("categoryDistribution", categoryDistribution);
        model.addAttribute("sentimentDistribution", sentimentDistribution);
        
        return "admin/dashboard";
    }
    
    // 新闻管理
    @GetMapping("/news")
    public String newsList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "15") int size,
            Model model) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "id"));
        Page<News> newsPage = newsService.findAll(pageable);
        
        model.addAttribute("newsPage", newsPage);
        
        return "admin/news-list";
    }
    
    @GetMapping("/news/add")
    public String addNewsForm(Model model) {
        model.addAttribute("news", new News());
        model.addAttribute("isEdit", false);
        
        return "admin/news-form";
    }
    
    @GetMapping("/news/edit/{id}")
    public String editNewsForm(@PathVariable Long id, Model model) {
        Optional<News> newsOpt = newsService.findById(id);
        
        if (newsOpt.isEmpty()) {
            return "redirect:/admin/news?error=notfound";
        }
        
        model.addAttribute("news", newsOpt.get());
        model.addAttribute("isEdit", true);
        
        return "admin/news-form";
    }
    
    @PostMapping("/news/save")
    public String saveNews(@ModelAttribute News news, @RequestParam(required = false) boolean isEdit) {
        if (isEdit) {
            newsService.updateNews(news);
        } else {
            newsService.save(news);
        }
        
        // 进行新闻分析
        newsAnalysisService.analyzeNews(news);
        
        return "redirect:/admin/news?success=true";
    }
    
    @GetMapping("/news/delete/{id}")
    public String deleteNews(@PathVariable Long id) {
        newsService.deleteById(id);
        return "redirect:/admin/news?deleted=true";
    }
    
    // 用户管理
    @GetMapping("/users")
    public String userList(Model model) {
        List<User> users = userService.findAll();
        model.addAttribute("users", users);
        
        return "admin/user-list";
    }
    
    @GetMapping("/users/add")
    public String addUserForm(Model model) {
        model.addAttribute("user", new User());
        model.addAttribute("isEdit", false);
        
        return "admin/user-form";
    }
    
    @GetMapping("/users/edit/{id}")
    public String editUserForm(@PathVariable Long id, Model model) {
        Optional<User> userOpt = userService.findById(id);
        
        if (userOpt.isEmpty()) {
            return "redirect:/admin/users?error=notfound";
        }
        
        model.addAttribute("user", userOpt.get());
        model.addAttribute("isEdit", true);
        
        return "admin/user-form";
    }
    
    @PostMapping("/users/save")
    public String saveUser(@ModelAttribute User user, @RequestParam(required = false) boolean isEdit) {
        if (isEdit) {
            userService.updateUser(user);
        } else {
            userService.register(user);
        }
        
        return "redirect:/admin/users?success=true";
    }
    
    @GetMapping("/users/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteById(id);
        return "redirect:/admin/users?deleted=true";
    }
}

